import MySelf from './compentes/Myself'
import './App.css'
import { useRef, useState, useEffect } from 'react'
import DanmakuCanvas from './compentes/Danmaku/DanmakuCanvas'
import type { DanmakuHandle } from './compentes/Danmaku/DanmakuCanvas'
import Exhibition3D from './compentes/Exhibition3D'
import { useTranslation } from 'react-i18next'
import { useSelector, useDispatch } from 'react-redux'
import { setTheme, setLanguage } from './store/settings'
import PermissionGate from './components/PermissionGate'
import UserInfo from './components/UserInfo'
import { Permission, isLoggedIn } from './utils/auth'
import { useNavigate } from 'react-router-dom'
function App() {
  const { t, i18n } = useTranslation()
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { theme, language } = useSelector((state: { settings: { theme: 'dark' | 'red', language: 'zh' | 'en' } }) => state.settings)
  
  const dmRef = useRef<DanmakuHandle | null>(null)
  const [text, setText] = useState('')
  const [opacity, setOpacity] = useState(1)
  const [speedLevel, setSpeedLevel] = useState(3) // 1-5 速度等级，3为中等速度
  const [danmakuMode, setDanmakuMode] = useState<'scroll' | 'top' | 'bottom'>('scroll')
  const [showExhibition, setShowExhibition] = useState(false)
  const [showAdvancedSettings, setShowAdvancedSettings] = useState(false)
  const [danmakuEnabled, setDanmakuEnabled] = useState(true)

  // 初始化弹幕控制器速度设置
  useEffect(() => {
    if (dmRef.current) {
      // 设置默认速度为中等（3级）
      const defaultSpeed = 100; // 中等速度
      dmRef.current.setFixedSpeed(defaultSpeed);
    }
  }, []);

  // 检查登录状态
  useEffect(() => {
    if (!isLoggedIn()) {
      navigate('/login')
    }
  }, [navigate])

  // 初始化主题设置
  useEffect(() => {
    // 页面加载时设置默认主题
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  // 处理弹幕开关
  const toggleDanmaku = () => {
    const newState = !danmakuEnabled;
    setDanmakuEnabled(newState);
    dmRef.current?.setEnabled(newState);
  };

  // 处理主题切换
  const handleThemeChange = (newTheme: 'dark' | 'red') => {
    dispatch(setTheme(newTheme));
    document.documentElement.setAttribute('data-theme', newTheme);
  };

  // 处理语言切换
  const handleLanguageChange = (newLanguage: 'zh' | 'en') => {
    dispatch(setLanguage(newLanguage));
    i18n.changeLanguage(newLanguage);
  };

  return (
    <div className='box w-full h-full' data-theme={theme}>
      {/* 用户信息显示 */}
      <UserInfo />
      
      {/* 主题和语言切换器 - 仅管理员可见 */}
      <PermissionGate permission={Permission.THEME_SWITCH}>
        <div style={{
          position: 'absolute',
          top: '20px',
          left: '220px', // 调整位置，避免与用户信息卡片重叠
          zIndex: 1000,
          display: 'flex',
          gap: '12px',
          alignItems: 'center'
        }}>
          {/* 主题切换器 */}
          <select 
            value={theme}
            onChange={(e) => handleThemeChange(e.target.value as 'dark' | 'red')}
            style={{
              padding: '8px 12px',
              borderRadius: '8px',
              background: 'rgba(255, 255, 255, 0.9)',
              border: '1px solid rgba(0, 0, 0, 0.2)',
              color: '#333',
              fontSize: '14px',
              cursor: 'pointer',
              outline: 'none'
            }}
          >
            <option value="dark">🌙 {t('theme.dark')}</option>
            <option value="red">❤️ {t('theme.light')}</option>
          </select>

          {/* 语言切换器 */}
          <PermissionGate permission={Permission.LANGUAGE_SWITCH}>
            <select 
              value={language}
              onChange={(e) => handleLanguageChange(e.target.value as 'zh' | 'en')}
              style={{
                padding: '8px 12px',
                borderRadius: '8px',
                background: 'rgba(255, 255, 255, 0.9)',
                border: '1px solid rgba(0, 0, 0, 0.2)',
                color: '#333',
                fontSize: '14px',
                cursor: 'pointer',
                outline: 'none'
              }}
            >
              <option value="zh">🇨🇳 中文</option>
              <option value="en">🇺🇸 English</option>
            </select>
          </PermissionGate>
        </div>
      </PermissionGate>
      {/* 3D展览馆按钮 - 所有用户都可以访问 */}
      <PermissionGate permission={Permission.EXHIBITION_ACCESS}>
        <button
          onClick={() => {
          // 播放开门音效
          if ((window as unknown as { audioManager?: { playSound: (sound: string) => void } }).audioManager) {
            (window as unknown as { audioManager: { playSound: (sound: string) => void } }).audioManager.playSound('doorOpen')
          }
            setShowExhibition(true)
          }}
          style={{
            position: 'absolute',
            top: '20px',
            right: '20px',
            zIndex: 1000,
            padding: '12px 24px',
            background: 'linear-gradient(135deg, #00ffff, #0088ff)',
            color: theme === 'red' ? '#333' : 'white',
            border: 'none',
            borderRadius: '25px',
            cursor: 'pointer',
            fontSize: '16px',
            fontWeight: '600',
            boxShadow: '0 4px 15px rgba(0, 255, 255, 0.3)',
            transition: 'all 0.3s ease',
            minWidth: '180px',
            textAlign: 'center'
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'translateY(-2px)';
            e.currentTarget.style.boxShadow = '0 6px 20px rgba(0, 255, 255, 0.4)';
          // 播放悬停音效
          if ((window as unknown as { audioManager?: { playSound: (sound: string) => void } }).audioManager) {
            (window as unknown as { audioManager: { playSound: (sound: string) => void } }).audioManager.playSound('hover')
          }
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'translateY(0)';
            e.currentTarget.style.boxShadow = '0 4px 15px rgba(0, 255, 255, 0.3)';
          }}
          onMouseDown={() => {
          // 播放点击音效
          if ((window as unknown as { audioManager?: { playSound: (sound: string) => void } }).audioManager) {
            (window as unknown as { audioManager: { playSound: (sound: string) => void } }).audioManager.playSound('click')
          }
          }}
        >
          🚀 {t('exhibition.enter3D')}
        </button>
      </PermissionGate>

      {/* 3D展览馆组件 */}
      {showExhibition && (
        <Exhibition3D onClose={() => setShowExhibition(false)} />
      )}

      <div className='box-list'>
        <div className='demo-area' style={{ position: 'relative' }}>
          {/* 视频播放 - 所有用户都可以观看 */}
          <PermissionGate permission={Permission.VIDEO_WATCH}>
            <video
              className='demo-video'
              controls
              autoPlay
              muted
              loop
            >
              <source src="https://prod-streaming-video-msn-com.akamaized.net/a8c412fa-f696-4ff2-9c76-e8ed9cdffe0f/604a87fc-e7bc-463e-8d56-cde7e661d690.mp4" type="video/mp4" />
              您的浏览器不支持视频播放。
            </video>
          </PermissionGate>
          
          {/* 弹幕系统 - 仅管理员可见 */}
          <PermissionGate permission={Permission.DANMAKU_CONTROL}>
            <DanmakuCanvas ref={dmRef} />
          </PermissionGate>
        </div>
        {/* 弹幕控制面板 - 可折叠设计 - 仅管理员可见 */}
        <PermissionGate permission={Permission.DANMAKU_CONTROL}>
          <div style={{
          position: 'absolute',
          left: '538px',
          top: '570px',
          width: '750px',
          background: 'rgba(0, 0, 0, 0.6)',
          borderRadius: '15px',
          padding: '10px 20px',
          color: '#fff',
          border: '1px solid rgba(255, 255, 255, 0.2)',
          backdropFilter: 'blur(10px)',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.3)',
          marginLeft: '-20px',
          transition: 'all 0.3s ease'
        }}>
          {/* 基础控制栏 - 始终显示 */}
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            height: '30px'
          }}>
            {/* 输入框 */}
            <input
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder={t('danmaku.inputPlaceholder')}
              onKeyPress={e => {
                if (e.key === 'Enter' && text.trim()) {
                  if (danmakuMode === 'scroll') {
                    dmRef.current?.send(text.trim());
                  } else if (danmakuMode === 'top') {
                    dmRef.current?.sendTop(text.trim());
                  } else if (danmakuMode === 'bottom') {
                    dmRef.current?.sendBottom(text.trim());
                  }
                  setText('');
                }
              }}
              style={{
                flex: 1,
                padding: '8px 15px',
                borderRadius: '8px',
                border: '1px solid rgba(255, 255, 255, 0.3)',
                background: 'rgba(255, 255, 255, 0.1)',
                color: '#fff',
                fontSize: '13px',
                outline: 'none',
                transition: 'all 0.3s ease'
              }}
            />

            {/* 发送按钮 */}
            <button
              onClick={() => {
                if (text.trim()) {
                  if (danmakuMode === 'scroll') {
                    dmRef.current?.send(text.trim());
                  } else if (danmakuMode === 'top') {
                    dmRef.current?.sendTop(text.trim());
                  } else if (danmakuMode === 'bottom') {
                    dmRef.current?.sendBottom(text.trim());
                  }
                  setText('');
                }
              }}
              style={{
                padding: '8px 16px',
                borderRadius: '8px',
                background: 'rgba(255, 255, 255, 0.2)',
                color: '#fff',
                border: '1px solid rgba(255, 255, 255, 0.3)',
                cursor: 'pointer',
                fontSize: '12px',
                fontWeight: '500',
                transition: 'all 0.3s ease',
                minWidth: '60px'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = 'rgba(255, 255, 255, 0.3)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'rgba(255, 255, 255, 0.2)';
              }}
            >
              {t('danmaku.send')}
            </button>

            {/* 表情按钮 */}
            <button
              onClick={() => dmRef.current?.showEmojiPicker()}
              style={{
                padding: '8px 12px',
                borderRadius: '8px',
                background: 'rgba(255, 255, 255, 0.2)',
                color: '#fff',
                border: '1px solid rgba(255, 255, 255, 0.3)',
                cursor: 'pointer',
                fontSize: '16px',
                fontWeight: '500',
                transition: 'all 0.3s ease',
                minWidth: '40px'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = 'rgba(255, 255, 255, 0.3)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'rgba(255, 255, 255, 0.2)';
              }}
              title="选择表情"
            >
              😊
            </button>

            {/* 弹幕开关按钮 */}
            <button
              onClick={toggleDanmaku}
              style={{
                padding: '8px 12px',
                borderRadius: '8px',
                background: danmakuEnabled
                  ? 'rgba(76, 175, 80, 0.8)'
                  : 'rgba(244, 67, 54, 0.8)',
                color: '#fff',
                border: '1px solid rgba(255, 255, 255, 0.3)',
                cursor: 'pointer',
                fontSize: '14px',
                fontWeight: '500',
                transition: 'all 0.3s ease',
                minWidth: '50px'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = danmakuEnabled
                  ? 'rgba(76, 175, 80, 1)'
                  : 'rgba(244, 67, 54, 1)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = danmakuEnabled
                  ? 'rgba(76, 175, 80, 0.8)'
                  : 'rgba(244, 67, 54, 0.8)';
              }}
              title={danmakuEnabled ? t('danmaku.off') : t('danmaku.on')}
            >
              {danmakuEnabled ? t('danmaku.on') : t('danmaku.off')}
            </button>

            {/* 设置按钮 */}
            <button
              onClick={() => setShowAdvancedSettings(!showAdvancedSettings)}
              style={{
                padding: '8px',
                borderRadius: '8px',
                background: showAdvancedSettings
                  ? 'rgba(255, 255, 255, 0.3)'
                  : 'rgba(255, 255, 255, 0.1)',
                color: '#fff',
                border: '1px solid rgba(255, 255, 255, 0.2)',
                cursor: 'pointer',
                fontSize: '16px',
                transition: 'all 0.3s ease',
                minWidth: '36px',
                height: '36px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                transform: showAdvancedSettings ? 'rotate(180deg)' : 'rotate(0deg)'
              }}
              title={showAdvancedSettings ? '收起设置' : '展开设置'}
            >
              ⚙️
            </button>
          </div>

          {/* 高级设置面板 - 可折叠 */}
          {showAdvancedSettings && (
            <div style={{
              marginTop: '15px',
              paddingTop: '15px',
              borderTop: '1px solid rgba(255, 255, 255, 0.1)',
              display: 'flex',
              flexWrap: 'wrap',
              gap: '15px',
              alignItems: 'center',
              animation: 'fadeIn 0.3s ease'
            }}>
              {/* 位置选择 */}
              <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                <label style={{ fontSize: '12px', color: 'rgba(255,255,255,0.8)', minWidth: '40px' }}>{t('danmaku.position')}:</label>
                <div style={{ display: 'flex', gap: '4px' }}>
                  {['scroll', 'top', 'bottom'].map((mode, index) => (
                    <button
                      key={mode}
                      onClick={() => {
                        setDanmakuMode(mode as 'scroll' | 'top' | 'bottom');
                        dmRef.current?.setGlobalDisplayMode(mode as 'scroll' | 'top' | 'bottom');
                      }}
                      style={{
                        padding: '4px 12px',
                        borderRadius: '6px',
                        fontSize: '11px',
                        background: danmakuMode === mode
                          ? 'rgba(255, 255, 255, 0.25)'
                          : 'rgba(255, 255, 255, 0.1)',
                        color: '#fff',
                        border: '1px solid rgba(255, 255, 255, 0.2)',
                        cursor: 'pointer',
                        transition: 'all 0.3s ease'
                      }}
                    >
                      {[t('danmaku.scroll'), t('danmaku.top'), t('danmaku.bottom')][index]}
                    </button>
                  ))}
                </div>
              </div>

              {/* 透明度控制 */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <label style={{ fontSize: '12px', color: 'rgba(255,255,255,0.8)', minWidth: '50px' }}>{t('danmaku.opacity')}:</label>
                <input
                  type='range'
                  min={0.3}
                  max={1}
                  step={0.05}
                  value={opacity}
                  onChange={e => { const v = parseFloat(e.target.value); setOpacity(v); dmRef.current?.setOpacity(v); }}
                  style={{
                    width: '80px',
                    accentColor: '#fff'
                  }}
                />
                <span style={{ fontSize: '11px', minWidth: '35px', color: 'rgba(255,255,255,0.7)' }}>
                  {Math.round(opacity * 100)}%
                </span>
              </div>

              {/* 速度控制 - 单滑块从慢到快 */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <label style={{ fontSize: '12px', color: 'rgba(255,255,255,0.8)', minWidth: '35px' }}>{t('danmaku.speed')}:</label>
                <div style={{
                  position: 'relative',
                  width: '180px',
                  height: '20px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px'
                }}>
                  {/* 慢速标签 */}
                  <span style={{
                    fontSize: '10px',
                    color: 'rgba(255,255,255,0.6)',
                    minWidth: '20px',
                    textAlign: 'left'
                  }}>
                    {t('danmaku.slow')}
                  </span>

                  {/* 速度滑块容器 */}
                  <div style={{
                    position: 'relative',
                    flex: 1,
                    height: '20px',
                    background: 'rgba(255, 255, 255, 0.1)',
                    borderRadius: '10px',
                    border: '1px solid rgba(255, 255, 255, 0.2)',
                    display: 'flex',
                    alignItems: 'center'
                  }}>
                    {/* 速度等级背景条 */}
                    <div style={{
                      position: 'absolute',
                      left: '0',
                      right: '0',
                      top: '50%',
                      height: '4px',
                      background: 'linear-gradient(to right, #ff6b6b, #ffa500, #32cd32, #00bfff, #8a2be2)',
                      borderRadius: '2px',
                      transform: 'translateY(-50%)',
                      pointerEvents: 'none'
                    }} />

                    {/* 速度滑块 */}
                    <input
                      type="range"
                      min="1"
                      max="5"
                      step="1"
                      value={speedLevel}
                      onChange={e => {
                        const level = parseInt(e.target.value);
                        setSpeedLevel(level);
                        // 将1-5等级转换为固定速度
                        const fixedSpeeds = [40, 65, 100, 140, 180]; // 1-5级对应的固定速度
                        const speed = fixedSpeeds[level - 1];
                        console.log('滑块调整到等级:', level, '对应速度:', speed);
                        dmRef.current?.setFixedSpeed(speed);
                      }}
                      className="speed-level-slider"
                    />
                  </div>

                  {/* 快速标签 */}
                  <span style={{
                    fontSize: '10px',
                    color: 'rgba(255,255,255,0.6)',
                    minWidth: '20px',
                    textAlign: 'right'
                  }}>
                    {t('danmaku.fast')}
                  </span>
                </div>

                {/* 当前速度等级显示 */}
                <div style={{
                  fontSize: '11px',
                  color: 'rgba(255,255,255,0.7)',
                  minWidth: '40px',
                  textAlign: 'center',
                  padding: '2px 8px',
                  background: 'rgba(255,255,255,0.1)',
                  borderRadius: '12px',
                  border: '1px solid rgba(255,255,255,0.2)'
                }}>
                  {[t('danmaku.slow'), t('danmaku.slow'), t('danmaku.medium'), t('danmaku.fast'), t('danmaku.fast')][speedLevel - 1]}
                </div>
              </div>

              {/* 清屏按钮 */}
              <button
                onClick={() => dmRef.current?.clear()}
                style={{
                  padding: '6px 12px',
                  borderRadius: '6px',
                  background: 'rgba(255, 77, 77, 0.3)',
                  color: '#fff',
                  border: '1px solid rgba(255, 77, 77, 0.5)',
                  cursor: 'pointer',
                  fontSize: '11px',
                  fontWeight: '500',
                  transition: 'all 0.3s ease'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = 'rgba(255, 77, 77, 0.5)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'rgba(255, 77, 77, 0.3)';
                }}
              >
                🗑️ {t('danmaku.clear')}
              </button>
            </div>
          )}
          </div>
        </PermissionGate>
        
        {/* 数字人组件 - 所有用户都可以查看，但只有管理员可以操作 */}
        <PermissionGate permission={Permission.DIGITAL_HUMAN_VIEW}>
          <div className='model-bottom-left'>
            <MySelf theme={theme}></MySelf>
          </div>
        </PermissionGate>
      </div>
    </div>
  )
}

export default App
